package cn.pkpm.air.job.feign.config;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author bbshi
 * @date 2023/1/4 11:39
 */
@Configuration
public class FeignConfiguration {

    private static final String HEADER_KEY_TOKEN = "token";
    private static final String HEADER_KEY_SOURCEFROM = "sourceFrom";

    /**
     * feign调用请求拦截
     * 通过feign调用其它服务时，feign会新建一个request请求，故原请求头里自定的参数会丢失
     * 拦截器作用：拦截旧请求，将旧请求中的自定义数据赋值给新请求头中
     *
     * @return
     */
    @Bean("feignRequestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes();
            HttpServletRequest oldRequest = requestAttributes.getRequest();

            requestTemplate.header(HEADER_KEY_TOKEN, oldRequest.getHeader(HEADER_KEY_TOKEN));
            requestTemplate.header(HEADER_KEY_SOURCEFROM, oldRequest.getHeader(HEADER_KEY_SOURCEFROM));
            // 添加 feign 调用标识
            requestTemplate.header("isFeign","true");
        };

    }
}
